package com.example.lib_common.mvi

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch
import retrofit2.http.Tag

abstract class BaseFragment<V : ViewBinding,VM : BaseViewModel<*,*>>  : Fragment(){
    protected lateinit var vm : VM
    abstract fun createVM():VM
    abstract fun createViewBinding():ViewBinding
    protected val inflater : LayoutInflater by lazy { LayoutInflater.from(context) }
    protected lateinit var v : V
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vm=createVM()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        v= createViewBinding() as V
        initStateFlow()
        return v.root
    }

    @SuppressLint("UnsafeRepeatOnLifecycleDetector")
    private fun initStateFlow() {
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestStateFlow.collect{
                    if (it.request){
                        showDialog()
                    }else if (it.complete){
                        hideDialog()
                    }else if(it.error){
                        showEmptyView()
                    }
                }
            }
        }
    }

    fun showDialog(){
        println("showDialog")
    }
    fun hideDialog(){
        println("hideDialog")
    }
    fun showEmptyView(){
        println("showEmptyView")
    }
    fun log(msg : String){
        Log.e(tag,msg)
    }
}